package com.linkcard.list.persistence;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.linkcard.commen.tools.Page;
import com.linkcard.list.model.Links;

public class LinksDaoImpl extends HibernateDaoSupport implements LinksDao {

	//添加友情链接
	public boolean addLinks(Links links) {
		try
		{
			this.getHibernateTemplate().save(links);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//获得友情链接
	public List linksList(final Page pageObj) {
		List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				Criteria criteria=session.createCriteria(Links.class);
						 if(pageObj!=null)
						 {
							 int rowCount=	(Integer)criteria.setProjection(Projections.count("id")).uniqueResult();
						     pageObj.setRowCount(rowCount);
				             pageObj.setTotalPage(rowCount);
				             criteria.setProjection(null);
				             criteria.setFirstResult((pageObj.getCurrentPage()-1)*pageObj.getPageSize());
					         criteria.setMaxResults(pageObj.getPageSize());
						 }
				return criteria.list();
			}
			
		});
		return list;
	}

	//获得友情链接
	public Links singleLinks(Integer id) {
		Links links=(Links)this.getHibernateTemplate().get(Links.class, id);
		return links;
	}

	//修改友情链接
	public boolean  modifyLinks(Links links) {
		try
		{
		Links lnk=(Links)this.getHibernateTemplate().get(Links.class, links.getId());
		BeanUtils.copyProperties(lnk, links);
		this.getHibernateTemplate().update(lnk);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//删除链接
	public boolean deleteLinks(Integer id) {
		try
		{
		Links links=(Links)this.getHibernateTemplate().get(Links.class, id);
		this.getHibernateTemplate().delete(links);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//获得推荐链接
	public List linksListForRecommend() {
		List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				Criteria criteria=session.createCriteria(Links.class);
						 criteria.add(Expression.eq("recommend", 1));
				return criteria.list();
			}
		});
		return list;
	}
	

}
